﻿using System;
using System.Linq;
using System.Collections.Generic;
using DBProvider;
using DBProvider.Providers;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;

namespace HealthCommunity.Controls
{
	public partial class UCExaminationEdit : System.Web.UI.UserControl
	{
		private IExaminationProvider _ExaminationProvider;
		private Dictionary<int, List<ExaminationAnswer>> _DicExmtQstnExmtAswr;
		private List<DrugStore> lstDrugStore;

		//private Examination _CurrentExamination;

		public int CurrentExaminationID
		{
			get
			{
				var id = CommonHelper.QueryStringInt("examinationid");

				if(id <= 0)
				{
					if(ViewState["CurrentExaminationID"] != null)
					{
						id = (int)ViewState["CurrentExaminationID"];
					}
				}

				return id;
			}
			set
			{
				ViewState["CurrentExaminationID"] = value;
			}
		}

		protected void Page_Load(object sender, EventArgs e)
		{
			if(!IsPostBack)
			{
				BindExaminationCategory();
				BindDrugStore();

			}

			//divimportqstncontainer.Visible = (CurrentExaminationID <= 0);
			//divimportexmt.Visible = (CurrentExaminationID > 0);
		}

		protected void Page_PreRender(object sender, EventArgs e)
		{
			divexistexmtqstn.Visible = (CurrentExaminationID > 0);
			if(CurrentExaminationID > 0)
			{
				BindCurrentExamination();
			}
		}

		protected void btnRemove_Click(object sender, EventArgs e)
		{
			if(lstMemberSelected.SelectedItem != null)
			{
				lstMemberSelected.Items.Remove(lstMemberSelected.SelectedItem);
			}
		}

		protected void btnAdd_Click(object sender, EventArgs e)
		{
			if(lstMember.SelectedItem != null)
			{
				var item = new System.Web.UI.WebControls.ListItem(lstMember.SelectedItem.Text, lstMember.SelectedItem.Value);

				if(!lstMemberSelected.Items.Contains(item))
				{
					lstMemberSelected.Items.Add(item);
				}
			}
		}

		protected void ddlDrugStore_SelectedIndexChanged(object sender, EventArgs e)
		{
			BindMember();
		}

		protected void rptExmtQstn_ItemDataBound(object sender, System.Web.UI.WebControls.RepeaterItemEventArgs e)
		{
			if(e.Item.DataItem != null)
			{
				var dataItem = e.Item.DataItem as ExaminationQuestion;
				var rptExmtQstnAswr = e.Item.FindControl("rptExmtQstnAswr") as System.Web.UI.WebControls.Repeater;

				if(_DicExmtQstnExmtAswr != null && _DicExmtQstnExmtAswr.Count > 0 && _DicExmtQstnExmtAswr.Keys.Contains(dataItem.ExaminationQuestionID))
				{
					rptExmtQstnAswr.DataSource = _DicExmtQstnExmtAswr[dataItem.ExaminationQuestionID];
					rptExmtQstnAswr.DataBind();
				}
			}
		}

		protected void btnSave_Click(object sender, EventArgs e)
		{
			if(_ExaminationProvider == null)
			{
				_ExaminationProvider = new ExaminationProvider();
			}

			var theExmt = new Examination();

			if(CurrentExaminationID > 0)
			{
				theExmt = _ExaminationProvider.GetExamination(CurrentExaminationID);
			}

			theExmt.ExaminationAddDate = DateTime.Now;
			theExmt.ExaminationCategoryID = int.Parse(ddlExmtCat.SelectedValue);
			theExmt.ExaminationDexcription = txtExaminationDescription.Text.Trim();
			theExmt.ExaminationName = txtExaminationName.Text.Trim();
			theExmt.ExaminationTime = int.Parse(txtExaminationTime.Text.Trim());
			theExmt.ExaminationTotalScore = int.Parse(txtExaminationTotalScore.Text.Trim());
			theExmt.IsPublic = chbIsPublic.Checked ? 1 : 0;

			if(CurrentExaminationID > 0)
			{
				//theExmt.ExaminationID = CurrentExaminationID;

				if(_ExaminationProvider.UpdateExamination(theExmt))
				{
					if(!chbIsPublic.Checked)
					{
						List<int> lstSelectedDrugStoreIDs = new List<int>();
						foreach(System.Web.UI.WebControls.ListItem item in chblstDrugStore.Items)
						{
							if(item.Selected)
							{
								lstSelectedDrugStoreIDs.Add(int.Parse(item.Value));
							}
						}

						List<RLT_ExaminationAndShareTo> lstExaminationAndShareTo = new List<RLT_ExaminationAndShareTo>();

						if(lstSelectedDrugStoreIDs.Count > 0)
						{
							foreach(var id in lstSelectedDrugStoreIDs)
							{
								var rltExaminationAndShareTo = new RLT_ExaminationAndShareTo() { ExaminationID = CurrentExaminationID, ShareToDrugStoreID = id };
								lstExaminationAndShareTo.Add(rltExaminationAndShareTo);
							}
						}

						if(lstMemberSelected.Items.Count > 0)
						{
							foreach(System.Web.UI.WebControls.ListItem item in lstMemberSelected.Items)
							{
								var memberID = int.Parse(item.Value);
								var rltExaminationAndShareTo = new RLT_ExaminationAndShareTo() { ExaminationID = CurrentExaminationID, ShareToMemberID = memberID };
								lstExaminationAndShareTo.Add(rltExaminationAndShareTo);
							}
						}

						_ExaminationProvider.SaveExaminationAndShareTo(CurrentExaminationID, lstExaminationAndShareTo);
					}

					ltrMsg.Text = "保存成功";
				}
				else
				{
					ltrMsg.Text = "保存失败了";
				}
			}
			else
			{
				var user = SiteContext.Current.CurrentUser;

				if(user != null)
				{
					theExmt.DrugStoreID = user.DrugStoreID;
				}

				var msg = string.Empty;
				theExmt = _ExaminationProvider.CreateExamination(theExmt, out msg);

				if(theExmt != null)
				{
					CurrentExaminationID = theExmt.ExaminationID;
					if(!chbIsPublic.Checked)
					{
						List<int> lstSelectedDrugStoreIDs = new List<int>();
						foreach(System.Web.UI.WebControls.ListItem item in chblstDrugStore.Items)
						{
							if(item.Selected)
							{
								lstSelectedDrugStoreIDs.Add(int.Parse(item.Value));
							}
						}

						List<RLT_ExaminationAndShareTo> lstNewExaminationAndShareTo = new List<RLT_ExaminationAndShareTo>();

						if(lstSelectedDrugStoreIDs.Count > 0)
						{
							foreach(var id in lstSelectedDrugStoreIDs)
							{
								var rltExaminationAndShareTo = new RLT_ExaminationAndShareTo() { ExaminationID = CurrentExaminationID, ShareToDrugStoreID = id };
								lstNewExaminationAndShareTo.Add(rltExaminationAndShareTo);
							}
						}

						if(lstMemberSelected.Items.Count > 0)
						{
							foreach(System.Web.UI.WebControls.ListItem item in lstMemberSelected.Items)
							{
								var memberID = int.Parse(item.Value);
								var rltExaminationAndShareTo = new RLT_ExaminationAndShareTo() { ExaminationID = CurrentExaminationID, ShareToMemberID = memberID };
								lstNewExaminationAndShareTo.Add(rltExaminationAndShareTo);
							}
						}

						if(lstNewExaminationAndShareTo.Count > 0)
						{
							_ExaminationProvider.CreateExaminationAndShareTo(lstNewExaminationAndShareTo);
						}
					}

					if(fuExmtQstn.HasFile)
					{
						SaveExaminationQuestion();
					}

					ltrMsg.Text = "保存成功";
				}
				else
				{
					ltrMsg.Text = "保存失败:" + msg;
				}
			}
		}

		private void BindCurrentExamination()
		{
			if(CurrentExaminationID > 0)
			{
				if(_ExaminationProvider == null)
				{
					_ExaminationProvider = new ExaminationProvider();
				}

				var theExamination = _ExaminationProvider.GetExamination(CurrentExaminationID);

				if(theExamination != null)
				{
					txtExaminationDescription.Text = theExamination.ExaminationDexcription;
					txtExaminationName.Text = theExamination.ExaminationName;
					txtExaminationTime.Text = theExamination.ExaminationTime.ToString();
					txtExaminationTotalScore.Text = theExamination.ExaminationTotalScore.ToString();

					if(theExamination.IsPublic != 1)
					{
						var examinationAndShareTo = _ExaminationProvider.GetExaminationAndShareToByExamination(CurrentExaminationID);

						if(examinationAndShareTo != null && examinationAndShareTo.Count > 0)
						{
							var examinationAndShareToDrugStore = examinationAndShareTo.Where(vs => vs.ShareToDrugStoreID > 0);
							var examinationAndShareToMember = examinationAndShareTo.Where(vs => vs.ShareToMemberID > 0);

							if(examinationAndShareToDrugStore != null)
							{
								var lstExaminationShareToDrugStore = examinationAndShareToDrugStore.ToList();

								if(lstExaminationShareToDrugStore.Count > 0)
								{
									foreach(System.Web.UI.WebControls.ListItem item in chblstDrugStore.Items)
									{
										var drugStoreID = int.Parse(item.Value);

										item.Selected = lstExaminationShareToDrugStore.Count(vs => vs.ShareToDrugStoreID == drugStoreID) > 0;
									}
								}
							}

							lstMemberSelected.Items.Clear();

							if(examinationAndShareToMember != null)
							{
								var lstExaminationShareToMember = examinationAndShareToMember.ToList();

								if(lstExaminationShareToMember.Count > 0)
								{
									var data = from vs in lstExaminationShareToMember
														 select new { UserCName = vs.User.UserCName, ShareToMemberID = vs.ShareToMemberID };

									foreach(var dataItem in data)
									{
										var item = new System.Web.UI.WebControls.ListItem(dataItem.UserCName, dataItem.ShareToMemberID.ToString());

										//if (!lstMemberSelected.Items.Contains(item))
										//{
										lstMemberSelected.Items.Add(item);
										//}
									}
								}
							}
						}
					}

					var lstExmtQstn = _ExaminationProvider.GetExaminationQuestionByExamination(CurrentExaminationID);
					var lstExmtAswr = _ExaminationProvider.GetExaminationAnswerByExamination(CurrentExaminationID);

					if(lstExmtQstn != null && lstExmtQstn.Count > 0)
					{
						_DicExmtQstnExmtAswr = new Dictionary<int, List<ExaminationAnswer>>();
						foreach(var eq in lstExmtQstn)
						{
							var qas = lstExmtAswr.Where(qa => qa.ExaminationQuestionID == eq.ExaminationQuestionID);

							if(qas != null)
							{
								_DicExmtQstnExmtAswr.Add(eq.ExaminationQuestionID, qas.ToList());
							}
						}
					}

					rptExmtQstn.DataSource = lstExmtQstn;
					rptExmtQstn.DataBind();
				}
			}
		}

		private decimal SaveExaminationQuestion()
		{
			decimal? totalScore = decimal.Zero;
			var lstExmtQstns = GetExaminationQuestion();

			if(lstExmtQstns != null && lstExmtQstns.Count > 0)
			{
				_ExaminationProvider = new ExaminationProvider();

				if(this.CurrentExaminationID > 0)
				{
					_ExaminationProvider.DeleteExaminationQuestionByExamination(this.CurrentExaminationID);
				}

				var msg = string.Empty;

				foreach(var eqItem in lstExmtQstns)
				{
					totalScore += eqItem.ExaminationQuestionScore;
					var eq = _ExaminationProvider.CreateExaminationQuestion(eqItem, true, out msg);
				}
			}

			return totalScore.Value;
		}

		private List<ExaminationQuestion> GetExaminationQuestion()
		{
			List<ExaminationQuestion> result = new List<ExaminationQuestion>();

			if(fuExmtQstn.HasFile)
			{
				if(System.IO.Path.GetExtension(fuExmtQstn.FileName).Equals(".xls"))
				{
					HSSFWorkbook wb = new HSSFWorkbook(fuExmtQstn.FileContent);
					var sheet = wb.GetSheetAt(0);
					var rows = sheet.GetRowEnumerator();
					if(rows.MoveNext())
					{
						while(rows.MoveNext())
						{
							IRow currentRow = (HSSFRow)rows.Current;

							if(currentRow.Cells.Count < 5)
							{
								break;
							}

							var eqContentCell = currentRow.GetCell(1);

							ExaminationQuestion eqItem = new ExaminationQuestion() { ExaminationID = CurrentExaminationID };
							if(eqContentCell != null && eqContentCell.CellType != CellType.BLANK && eqContentCell.CellType != CellType.ERROR && eqContentCell.CellType != CellType.Unknown)
							{
								eqItem.ExaminationQuestionContent = eqContentCell.ToString();
							}

							var eqScoreCell = currentRow.GetCell(2);

							if(eqScoreCell != null && eqScoreCell.CellType != CellType.BLANK && eqScoreCell.CellType != CellType.ERROR && eqScoreCell.CellType != CellType.Unknown)
							{
								var score = decimal.Zero;
								if(decimal.TryParse(eqScoreCell.ToString().Trim(), out score))
								{
									eqItem.ExaminationQuestionScore = score;
								}
							}

							var eqAnswerCell = currentRow.GetCell(3);

							if(eqAnswerCell != null && eqAnswerCell.CellType != CellType.BLANK && eqAnswerCell.CellType != CellType.ERROR && eqAnswerCell.CellType != CellType.Unknown)
							{
								eqItem.ExaminationQuestionAnswer = eqAnswerCell.ToString().Trim();
							}

							eqItem.ExaminationAnswers = new System.Data.Linq.EntitySet<ExaminationAnswer>();

							for(var i = 4; i < currentRow.LastCellNum; i++)
							{
								var eaItem = new ExaminationAnswer();

								var eaCell = currentRow.GetCell(i);

								if(eaCell != null && eaCell.CellType != CellType.BLANK && eaCell.CellType != CellType.ERROR && eaCell.CellType != CellType.Unknown)
								{
									eaItem.ExaminationAnswerContent = eaCell.ToString().Trim();
									eaItem.ExaminationAnswerNum = ((char)((int)'A' + (i - 4))).ToString();

									eqItem.ExaminationAnswers.Add(eaItem);
								}
							}

							result.Add(eqItem);
						}
					}
				}
			}

			return result;
		}

		private void BindExaminationCategory()
		{
			if(_ExaminationProvider == null)
			{
				_ExaminationProvider = new ExaminationProvider();
			}

			ddlExmtCat.Items.Clear();
			ddlExmtCat.DataSource = _ExaminationProvider.GetAllExaminationCategory();
			ddlExmtCat.DataBind();
		}

		private void BindDrugStore()
		{
			chblstDrugStore.Items.Clear();
			chblstDrugStore.DataSource = GetDrugStore();
			chblstDrugStore.DataBind();

			ddlDrugStore.Items.Clear();
			ddlDrugStore.DataSource = GetDrugStore();
			ddlDrugStore.DataBind();

			BindMember();
		}

		private void BindMember()
		{
			if(!string.IsNullOrWhiteSpace(ddlDrugStore.SelectedValue))
			{
				var selectedDrugStoreID = int.Parse(ddlDrugStore.SelectedValue);

				var userProvider = new UserProvider();

				lstMember.DataSource = userProvider.GetUserByDrugStore(selectedDrugStoreID, true);
				lstMember.DataBind();
			}
		}

		private List<DrugStore> GetDrugStore()
		{
			List<DrugStore> result;

			if(this.lstDrugStore != null)
			{
				result = lstDrugStore;
			}
			else
			{
				var drugStoreProvider = new DrugStoreProvider();

				lstDrugStore = drugStoreProvider.GetAllDrugStore();

				result = lstDrugStore;
			}

			return result;
		}
	}
}